#!/usr/bin/env bash

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

set -o pipefail

SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
SPARK_ROOT_DIR="$(dirname $SCRIPT_DIR)"
LINT_JS_REPORT_FILE_NAME="$SPARK_ROOT_DIR/dev/lint-js-report.log"
LINT_TARGET_FILES=(
  "$SPARK_ROOT_DIR/core/src/main/resources/org/apache/spark/ui/static/"
  "$SPARK_ROOT_DIR/sql/core/src/main/resources/org/apache/spark/sql/execution/ui/static/"
  "$SPARK_ROOT_DIR/docs/js"
  "$SPARK_ROOT_DIR/ui-test/tests/"
)

if ! type "npm" > /dev/null; then
  echo "ERROR: You should install npm"
  exit 1
fi

if ! type "npx" > /dev/null; then
  echo "ERROR: You should install npx"
  exit 1
fi

cd $SCRIPT_DIR

if ! npm ls eslint > /dev/null; then
  npm ci eslint
fi

npx eslint -c "$SPARK_ROOT_DIR/dev/eslint.json" ${LINT_TARGET_FILES[@]} | tee "$LINT_JS_REPORT_FILE_NAME"
lint_status=$?

if [ "$lint_status" = "0" ] ; then
   echo "lint-js checks passed."
else
  echo "lint-js checks failed."
fi

exit "$lint_status"
